package com.woniu.woniu_bx.filter;

import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 用户登录过滤器，对一些需要登录才能请求的数据进行校验是否已登录
 *
 * @author 王泰元
 * @date 2022/09/07 09:23
 */
@Slf4j
public class UserLoginFilter extends OncePerRequestFilter {

    // 只有这里面的路径要求登录
    private final List<String> requireLoginURI = new ArrayList<>(Arrays.asList(
            // 下单
            "/order/add",
            // 动态
            "/community",
            // 聊天
            "/chat"));

    @Override
    protected void doFilterInternal(@NotNull HttpServletRequest request,
                                    @NotNull HttpServletResponse response,
                                    @NotNull FilterChain filterChain) throws ServletException, IOException {

        String requestURI = request.getRequestURI();
        if (isRequireLoginURI(requestURI)) {
//        if (false) {
            log.debug("请求路径：{}", requestURI + " ----- 要求登录");

            // 如果请求头中的 userId 为空或者不存在，返回 401
            if (!StringUtils.hasLength(request.getHeader("userId"))) {
                response.sendRedirect("/login/unAuthority");
            } else {
                filterChain.doFilter(request, response);
            }
        } else {
            log.debug("请求路径：{}", requestURI + " ----- 放行");
            filterChain.doFilter(request, response);
        }
    }

    // 判断路径是否要求登录
    private boolean isRequireLoginURI(String requestURI) {
        for (String s : requireLoginURI) {
            if (requestURI.contains(s)) {
                return true;
            }
        }
        return false;
    }
}
